package com.gnerv.pabu.basic.core.controller;

import com.gnerv.pabu.basic.core.entity.Result;
import com.gnerv.pabu.basic.core.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

/**
 * <p>
 * 基础平台-部署信息 前端控制器
 * </p>
 *
 * @author Gnerv LiGen
 * @since 2019-10-10
 */
@Slf4j
@Api(tags = "文件 管理")
@CrossOrigin
@RestController
@RequestMapping(value = "/api/platform/file")
public class FileController {


    @ApiOperation(value = "上传 文件 ")
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public Result uploadFile(@RequestParam("files") MultipartFile[] files) {
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                throw new BusinessException("上传文件不能为空！");
            }
        }
        return Result.response();
    }


    @ApiOperation(value = "下载 文件 ")
    @RequestMapping(value = "download", method = RequestMethod.GET)
    public Result downloadFile() {
        return Result.response();
    }

    @RequestMapping(value = "download/{type}", method = RequestMethod.GET)
    public void download(@PathVariable(value = "type", required = false) int type,
                         HttpServletResponse response) {
        try {
            //设置文件名和编码
            String fileName = URLEncoder.encode("demo.mp4", "UTF-8");
            if (type == 1) {
                response.setHeader("Content-Disposition", "inline;filename=" + fileName);
            } else {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            }
            FileCopyUtils.copy(new FileInputStream(new File("C:\\Users\\ligen\\Pictures\\Camera Roll\\demo.mp4")), response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
